package SystemB;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import EventPackage.Participant;

public class SprinklerController extends Participant {
	private static final int sprinklerEventID = 13;
	private static final int sprinklerConfirmID = -13;
	private static final int sprinklerTimerID = 14;
	private static final int fireAlarmID = 6;
	private static final String fireAlarmMessage = "FA";
	
	private Timer autoTimer;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SprinklerController sc = new SprinklerController("Sprinkler Controller", 91, "Sprinkler Controller");
		sc.run(args);
	}

	public SprinklerController(String name, int subSystemHaldEndID, String sensor_name){
		super();
		
		this.name = name;
		mwXpos = 0; 
		mwYpos = 0; 
		mwHeight = 198;
		mwWidth = 550;
		
		setParameters(name, mwXpos, mwYpos, mwHeight, mwWidth, subSystemHaldEndID, sensor_name);
	}
	
	@Override
	protected void customHalt() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void initialPostPhase() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void handlePhase() {
		int eventID = Evt.GetEventId();
		String message = Evt.GetMessage();
		
		if(eventID == sprinklerEventID){
			if(message.equals("SP1")){
				mw.WriteMessage("Sprinkler on");
				postEvent(sprinklerConfirmID, message);
				if(autoTimer != null){
					autoTimer.stop();
					autoTimer = null;
				}
			} else if (message.equals("SP0")){
				mw.WriteMessage("Sprinkler off");
				postEvent(sprinklerConfirmID, message);
				if(autoTimer != null){
					autoTimer.stop();
					autoTimer = null;
				}
			}
		}
		
		if(eventID == fireAlarmID && message.equals(fireAlarmMessage)){
			ActionListener autoOn = new ActionListener(){
				private int maxcount = 15;
				private int count = 0;
				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					count++;
					mw.WriteMessage((maxcount - count) + " seconds till sprinklers activate");
					if(count == maxcount){
						mw.WriteMessage("Sprinkler on");
						postEvent(sprinklerConfirmID, "SP1");
						autoTimer.stop();
						autoTimer = null;
					}
				}
			};
			
			autoTimer = new Timer(1000, autoOn);
			postEvent(sprinklerTimerID, "SP");
			mw.WriteMessage("Timer started!");
			autoTimer.start();
		}
	}

	@Override
	protected void finalPostPhase() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void beforeLooping() {
		// TODO Auto-generated method stub
		
	}

}
